package com.wbao.dianniu.customView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.ColorInt;
import android.text.Html;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;

import com.wbao.dianniu.utils.Utils;

import java.io.InputStream;
import java.util.ArrayList;

/**
 * Created by Administrator on 2017/9/11.
 */

@SuppressLint("AppCompatCustomView")
public class HtmlTextView2 extends TextView {

    public static final String TAG = "HtmlTextView";
    public static final boolean DEBUG = false;

    public HtmlTextView2(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public HtmlTextView2(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HtmlTextView2(Context context) {
        super(context);
    }

    /**
     * @param is
     * @return
     */
    static private String convertStreamToString(InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");

        return s.hasNext() ? s.next() : "";
    }

    /**
     * Parses String containing HTML to Android's Spannable format and displays
     * it in this TextView.
     *
     * @param html String containing HTML, for example: "<b>Hello world!</b>"
     */
    public void setHtmlFromString(String html, boolean useLocalDrawables) {
        Html.ImageGetter imgGetter;

        if (useLocalDrawables) {
            imgGetter = new LocalImageGetter(getContext());
        } else {
            imgGetter = new UrlImageGetter(this, getContext());
        }
        // 处理代码显示问题.空格及换行不显示...
        html = html.replaceAll("\n", "<br/>").replaceAll(" ", " ");
        // this uses Android's Html class for basic parsing, and HtmlTagHandler
        setText(Html.fromHtml(html, imgGetter, new HtmlTagHandler()));

        // make links work
//        setMovementMethod(LinkMovementMethod.getInstance());
        this.setMovementMethod(LinkMovementMethodExt.getInstance(handler, ImageSpan.class));
//        this.setTextColor(getResources().getColor(android.R.color.secondary_text_dark_nodisable));
    }

    public static class LinkMovementMethodExt extends LinkMovementMethod {

        private static LinkMovementMethodExt sInstance;
        private Handler handler = null;
        private Class spanClass = null;

        public static MovementMethod getInstance(Handler _handler, Class _spanClass) {
            if (sInstance == null) {
                sInstance = new LinkMovementMethodExt();
                ((LinkMovementMethodExt) sInstance).handler = _handler;
                ((LinkMovementMethodExt) sInstance).spanClass = _spanClass;
            }
            return sInstance;
        }

        int x1;
        int x2;
        int y1;
        int y2;

        @Override
        public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                x1 = (int) event.getX();
                y1 = (int) event.getY();
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                x2 = (int) event.getX();
                y2 = (int) event.getY();
                if (Math.abs(x1 - x2) < 10 && Math.abs(y1 - y2) < 10) {
                    x2 -= widget.getTotalPaddingLeft();
                    y2 -= widget.getTotalPaddingTop();
                    x2 += widget.getScrollX();
                    y2 += widget.getScrollY();
                    Layout layout = widget.getLayout();
                    int line = layout.getLineForVertical(y2);
                    int off = layout.getOffsetForHorizontal(line, x2);
                    /**             * get you interest span             */
                    Object[] spans = buffer.getSpans(off, off, spanClass);
                    if (spans.length != 0) {
                        Selection.setSelection(buffer,
                                buffer.getSpanStart(spans[0]),
                                buffer.getSpanEnd(spans[0]));
                        MessageSpan obj = new MessageSpan();
                        obj.setObj(spans);
                        obj.setView(widget);
                        Message message = handler.obtainMessage();
                        message.obj = obj;
                        message.what = 200;
                        message.sendToTarget();
                        return true;
                    }
                }
            }
            return super.onTouchEvent(widget, buffer, event);
        }
    }

    // make links and image work
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int what = msg.what;
            if (what == 200) {
                MessageSpan ms = (MessageSpan) msg.obj;
                Object[] spans = (Object[]) ms.getObj();
                for (Object span : spans) {
                    if (span instanceof ImageSpan) {
//                        System.out.println("点击了图片:" + ((ImageSpan) span).getSource());
                        //处理自己的逻辑
                        ArrayList<String> list = new ArrayList<String>();
                        list.add(((ImageSpan) span).getSource());
                        Utils.imageBrower(ms.getView().getContext(), 0, list);

                    }
                }
            }else if(what == 300) {


            }
        }
    };

    public static class MessageSpan {
        private Object obj;
        private TextView view;

        public Object getObj() {
            return obj;
        }

        public void setObj(Object obj) {
            this.obj = obj;
        }

        public TextView getView() {
            return view;
        }

        public void setView(TextView view) {
            this.view = view;
        }
    }

    public void setSpanLink(String text, String sign, boolean isUnderLineVisiable,int start,int counts) {
        setSpanLink(start, start + counts, sign, isUnderLineVisiable, 0);
    }

    /**
     * 设置文字链接
     *
     * @param start               开始的位置
     * @param end                 结束的位置
     * @param sign                设置链接对应的标识，供给回调的时候判断
     * @param isUnderLineVisiable 是否显示下划线
     * @param color               文字的颜色
     */
    public void setSpanLink(int start, int end, String sign, boolean isUnderLineVisiable, @ColorInt int color) {
        /*try {
            //防止字符不存在异常
            setSpann(createSpan(getText(), new ClickSpan(new ClickListener(getText().subSequence(start, end), sign), isUnderLineVisiable, color), start, end));
            setMovementMethod(SpanTextView.LocalLinkMovementMethod.getInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }*/

    }
    public void setSpann(SpannableString spannableString) {
        if (spannableString == null) {
            return;
        }
        setText(spannableString);
    }

    public SpannableString createSpan(CharSequence text, Object spann, int start, int end) {

        if (start < 0 || end <= 0 || spann == null) {
            return null;
        }

        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(spann, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        return spannableString;
    }
}
